package com.barry.io.utils;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson2.*;

/**
 * 通义千问VL-Max模型的视觉理解能力最强
 * 参考: https://help.aliyun.com/zh/model-studio/vision/#5aab095b1daqg
 * 根据在线图片进行AI诊断分析
 * */
@Slf4j
public class OnlineImageDiagnosis {
    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        long startTime = System.currentTimeMillis();

        String imageUrl = "https://taiyi.oss-accelerate.aliyuncs.com/Diabetes_APP/user/166080496432067325/consultation/tongue/2025-08-28-16-41-37/1756370497052.jpg";
        //String text = "根据舌面进行中医AI诊断，出一个报告，报告维度有体质名称，中医证型，健康分值，体质分析，典型特征，风险预警，异常分析，调理建议等, 请把接口返回的MultiModalConversationResult中的MultiModalMessage的内容text内容以JSON格式返回";
//        String text = "根据舌面进行中医AI诊断，出一个报告，报告维度有体质名称，中医证型，健康分值，体质分析，典型特征，风险预警，异常分析，调理建议等, " +
//                "请把接口返回的MultiModalConversationResult中的MultiModalMessage的内容text内容以HashMap格式返回," +
//                "HashMap的体质名称HASHKEY为:tizhimingcheng,中医证型HASHKEY为:zhongyizhengxing,健康分值HASHKEY为:jiankangfenzhi,体质分析HASHKEY为:tizhifenxi," +
//                "典型特征HASHKEY为:dianxingtezheng,风险预警HASHKEY为:fengxianyujing,异常分析HASHKEY为:yichangfenxi,调理建议HASHKEY为:tiaolijianyi." +
//                "其他所有内容都存储在HASHKEY:others中。";
        String text = "根据舌面进行中医AI诊断，出一个报告，报告维度有体质名称，中医证型，健康分值，体质分析，典型特征，风险预警，异常分析，调理建议等, " +
                "请把接口返回的MultiModalConversationResult中的MultiModalMessage的内容text内容以JSON格式返回。";
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMessage = MultiModalMessage.builder().role(Role.SYSTEM.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("text", "You are a helpful assistant."))).build();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", imageUrl),
                        Collections.singletonMap("text", text))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(Const.ALI_BAI_LIAN_API_KEY)
                .model(Const.ALI_BAI_LIAN_MODEL_VL_MAX)  // 此处以qwen-vl-max-latest为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/models
                .messages(Arrays.asList(systemMessage, userMessage))
                .build();
        MultiModalConversationResult result = conv.call(param);
        String resp = result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text").toString();
        log.info("AI返回内容为: {}", resp);
        long end = System.currentTimeMillis();
        log.info("耗时: {}ms", (end - startTime));
        if (StringUtils.isNotBlank(resp)) {
            String content = resp;
            int index = content.lastIndexOf("}")+ 1;
            log.info("数据处理[index]为: {}", index);
            content = content.substring(0, index);
            content = content.replaceAll("```json", "");
            log.info("数据处理[content]为: {}", content);
            //Map<String, Object> map = JSON.parseObject(content, Map.class);
            Map<String, Object> map = JSON.parseObject(content, Map.class);
            String constitutionName = map.get("体质名称").toString();
            String syndromeType = map.get("中医证型").toString();
            int healthScore = (int) map.get("健康分值");
            String constitutionAnalysis = map.get("体质分析").toString();
            String typicalFeatures = map.get("典型特征").toString();
            String riskWarning = map.get("风险预警").toString();
            String abnormalAnalysis = map.get("异常分析").toString();
            String conditioningSuggestions = map.get("调理建议").toString();
            log.info("体质名称: {}", constitutionName);
            log.info("中医证型: {}", syndromeType);
            log.info("健康分值: {}", healthScore);
            log.info("体质分析: {}", constitutionAnalysis);
            log.info("典型特征: {}", typicalFeatures);
            log.info("风险预警: {}", riskWarning);
            log.info("异常分析: {}", abnormalAnalysis);
            log.info("调理建议: {}", conditioningSuggestions);
        }
    }
    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            log.error(e.getMessage(), e);
        }
        System.exit(0);
    }
}